package net.dgg.rz.evaluating.controller;

import com.alibaba.fastjson.JSONArray;
import net.dgg.framework.tac.mongo.utils.DggMongoUtils;
import net.dgg.framework.tac.redis.utils.DggRedisUtils;
import net.dgg.framework.tac.utils.DggValidateUtil;
import net.dgg.framework.tac.utils.bean.DggRestResponse;
import net.dgg.framework.tac.utils.idutil.DggKeyWorker;
import net.dgg.framework.tac.utils.web.commmon.DggBaseController;
import net.dgg.rz.common.constant.ScProductConstant;
import net.dgg.rz.common.excption.CommonExcption;
import net.dgg.rz.common.service.CommonMangerExtService;
import net.dgg.rz.common.utils.Convertor;
import net.dgg.rz.common.utils.StringUtils;
import net.dgg.rz.evaluating.entity.EvaluatingBaseChannel;
import net.dgg.rz.evaluating.entity.EvaluatingChannelField;
import net.dgg.rz.evaluating.entity.EvaluatingResults;
import net.dgg.rz.evaluating.entity.EvaluatingTestPaper;
import net.dgg.rz.evaluating.entity.dto.OptionsDto;
import net.dgg.rz.evaluating.entity.dto.SubjectOptionsDto;
import net.dgg.rz.evaluating.service.EvaluatingService;
import net.dgg.tmd.foundation.platform.common.redis.RConnectionFactory;
import net.dgg.tmd.foundation.platform.treebook.entity.TreeBook;
import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.binding.BindingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by zyou on 2019/5/28.
 */
@Controller
@RequestMapping("/api/evaluating")
public class ApiEvaluatingController extends DggBaseController {
    @Autowired
    private EvaluatingService evaluatingService;

    @Autowired
    private CommonMangerExtService commonMangerExtService;

    /**
     * 地域选择
     * @param params
     * @param model
     * @return
     */
    @RequestMapping(value = "/area_select")
    public String areaSelect(@RequestParam Map params, Model model) {
        Integer paperType = params.get("paperType")==null?1:Integer.parseInt(params.get("paperType").toString());
        String paperAreaCode = params.get("paperAreaCode")==null?"":params.get("paperAreaCode").toString();
        //查询已配置地域
        List<TreeBook> treeBookList = commonMangerExtService.queryTreeBookListByCode("RZSC_RATING_AREA", 1, 1);
        model.addAttribute("treeBookList",treeBookList);
        model.addAttribute("paperType",paperType);
        model.addAttribute("paperAreaCode",paperAreaCode);
        return "rzsc/evaluating/html/customer_rating_area";
    }
    /**
     * 根据试题类型返回试题
     * @param params
     * @param model
     * @return
     */
    @RequestMapping(value = "/query_paper_by_paper_type")
    public String queryPaperByPaperType(@RequestParam Map params, Model model) {
        Integer paperType = params.get("paperType")==null?1:Integer.parseInt(params.get("paperType").toString());
        String paperAreaCode = params.get("paperAreaCode")==null?"":params.get("paperAreaCode").toString();
        //根据code查询是按照什么题目类型
        EvaluatingTestPaper evaluatingTestPaper = new EvaluatingTestPaper();
        evaluatingTestPaper.setFlag(0);
        evaluatingTestPaper.setPaperCategory(paperType);
        evaluatingTestPaper.setPaperAreaCode(paperAreaCode);
        String title = "客户评级";
        if(paperType != 1){
            title = "税金贷";
        }
        model.addAttribute("title",title);
        model.addAttribute("paperCategory",paperType);
        model.addAttribute("paperAreaCode",paperAreaCode);
        Map treeBook = null;
        if(StringUtils.isNotEmpty(paperAreaCode)){
            treeBook = commonMangerExtService.getTreeBookObj(paperAreaCode);
        }
        if(null != treeBook && treeBook.size()>0){
            model.addAttribute("paperAreaName",treeBook.get("name"));
        }else{
            model.addAttribute("paperAreaName","成都");
        }
        List<EvaluatingTestPaper> evaluatingTestPaperList = evaluatingService.selectAll(evaluatingTestPaper);
        model.addAttribute("evaluatingTestPaperList",evaluatingTestPaperList);
        return "rzsc/evaluating/html/customer_rating_list";
    }

    /**
     * 根据code试题及关联题目，选项
     */
    @RequestMapping(value = "/query_paper")
    public String queryPaper(@RequestParam Map params, Model model) {
        String code = params.get("codeType")==null?"":params.get("codeType").toString();
        if(StringUtils.isEmpty(code)){
            return "";
        }
        if(code.contains("?")){
            code = org.apache.commons.lang3.StringUtils.substringBeforeLast(code,"?");
        }
        //根据code查询是按照什么题目类型
        EvaluatingTestPaper evaluatingTestPaper = new EvaluatingTestPaper();
        evaluatingTestPaper.setFlag(0);
        evaluatingTestPaper.setPaperCode(code);
        evaluatingTestPaper = evaluatingService.selectOne(evaluatingTestPaper);
        //试卷类型(1、不按照题目顺序填写；2、按照题目顺序答题)
        Integer paperType = evaluatingTestPaper.getPaperCategory();
        model.addAttribute("baseScore",Convertor.rvZeroAndDot(evaluatingTestPaper.getPaperScore()==null?"0":evaluatingTestPaper.getPaperScore().toString()));
        model.addAttribute("code",evaluatingTestPaper.getPaperCode());
        if(evaluatingTestPaper == null || paperType==null){
            return "";
        }else if (paperType.intValue()==1){
            //根据试题id查询题目
            Map paperParams = new HashMap();
            paperParams.put("paperId",evaluatingTestPaper.getId());
            List<SubjectOptionsDto> subjectOptionsDtos = evaluatingService.queryPaperSubjectByPaperId(paperParams);
            model.addAttribute("paperId",evaluatingTestPaper.getId());
            model.addAttribute("subjectOptionsDtos",subjectOptionsDtos);
            return "rzsc/evaluating/html/customer_rating";
        }else if (paperType.intValue()==2){
            //根据试题id查询题目
            Map paperParams = new HashMap();
            paperParams.put("paperId",evaluatingTestPaper.getId());
            List<SubjectOptionsDto> countSub = evaluatingService.queryPaperSubjectByPaperId(paperParams);
            //序号
            int subjectSort = params.get("subjectSort")==null?1:Integer.parseInt(params.get("subjectSort").toString());
            Long keyId = params.get("keyId")==null?DggKeyWorker.nextId():Long.parseLong(params.get("keyId").toString());
            paperParams.put("subjectSort",subjectSort);
            List<SubjectOptionsDto> subjectOptionsDtos = evaluatingService.queryPaperSubjectByPaperId(paperParams);
            SubjectOptionsDto subjectOptionsDto = (subjectOptionsDtos==null||subjectOptionsDtos.size()==0)?null:subjectOptionsDtos.get(0);
            model.addAttribute("subjectName",subjectOptionsDto == null?null:subjectOptionsDto.getSubjectName());
            model.addAttribute("optionsList",subjectOptionsDto == null?null:subjectOptionsDto.getOptionsList());
            model.addAttribute("count",countSub==null?0:countSub.size());
            model.addAttribute("sort",subjectSort);
            model.addAttribute("keyId",keyId);
            return "rzsc/evaluating/html/customer_taxes";
        }else {
            return "";
        }

    }

    /**
     * 提交试题
     */
    @RequestMapping(value = "/submit_paper_subject")
    @ResponseBody
    public DggRestResponse submitPaperSubject(@RequestParam Map params) {
        try {
            DggValidateUtil.notNull(params.get("submitJson"),CommonExcption.class,"参数为空");
            DggValidateUtil.notNull(params.get("baseScore"),CommonExcption.class,"基础分为空");
            List<SubjectOptionsDto> subjectOptionsDtos=JSONArray.parseArray(params.get("submitJson").toString(), SubjectOptionsDto.class);
            //计算结果
            //分数
            BigDecimal score = new BigDecimal(params.get("baseScore").toString());
            //试卷Id
            Long paperId = new Long(params.get("paperId").toString());
            //查询评估结果
            EvaluatingResults evaluatingResults = evaluatingService.findResultsBypaperId(paperId);
            Long resultsId =  evaluatingResults.getId();
            //加分项
            List<Map> addtractions = new ArrayList<>();
            Map addtraction = null;
            //减分项
            List<Map> subtractions = new ArrayList<>();
            Map subtraction = null;
            for (SubjectOptionsDto subjectOptionsDto:subjectOptionsDtos){
                List<OptionsDto> optionsDtos = subjectOptionsDto.getOptionsList();
                if(optionsDtos != null && optionsDtos.size()>0){
                    for (OptionsDto optionsDto:optionsDtos) {
                        String optionsName = optionsDto.getOptionsName();
//                        String optionsCode = optionsDto.getOptionsCode();
                        int optionsScoreType = optionsDto.getOptionsScoreType();
                        Double optionsScore = optionsDto.getOptionsScore();
                        //加分
                        if(optionsScoreType==1&&optionsScore != 0){
                            addtraction = new HashMap();
                            addtraction.put("subjectName",subjectOptionsDto.getSubjectName());
                            addtraction.put("optionsName",optionsName);
                            addtraction.put("optionsScore", Convertor.rvZeroAndDot(optionsScore.toString()));
                            score = score.add(new BigDecimal(optionsScore));
                            addtractions.add(addtraction);
                        }
                        //减分
                        if(optionsScoreType==2 && optionsScore != 0){
                            subtraction = new HashMap();
                            subtraction.put("subjectName",subjectOptionsDto.getSubjectName());
                            subtraction.put("optionsName",optionsName);
                            subtraction.put("optionsScore", Convertor.rvZeroAndDot(optionsScore.toString()));
                            subtractions.add(subtraction);
                            score = score.subtract(new BigDecimal(optionsScore));

                        }
                    }
                }

            }

            //根据分数查询所匹配的等级等内容
            Map map = new HashMap();
            map.put("score",score.doubleValue());
            map.put("resultsId",resultsId);
            Map level = evaluatingService.selectLevel(map);
            //数据封装存储redis
            if(level == null){
                level = new HashMap();
            }
            level.put("score",Convertor.rvZeroAndDot(score.toString()));
            level.put("addtractions",addtractions);
            level.put("subtractions",subtractions);
            level.put("rate",level.get("rate"));
            level.put("benchmark",level.get("benchmark"));
            level.put("combined",level.get("combined"));
            Long key = DggKeyWorker.nextId();
            DggRedisUtils.setExJson(key+"",level,3600);
            return this.getSuccessResponse(key);
        }catch (CommonExcption e){
            e.printStackTrace();
            logger.error(e.getMessage());
            return this.getFailResponse(e.getMessage());
        }catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return this.getFailResponse(ScProductConstant.SYS_ERROR);
        }
    }

    /**
     * 根据code试题及关联题目，选项
     */
    @RequestMapping(value = "/customer_score")
    public String customerScore(String key, Model model) {
        if(StringUtils.isEmpty(key)){
            return "";
        }
        //查询redis
        Map result = DggRedisUtils.getJson(key,Map.class);
        model.addAttribute("result",result);
        return "rzsc/evaluating/html/customer_score";
    }

    /**
     * 提交试题
     */
    @RequestMapping(value = "/submit_options_channel")
    @ResponseBody
    public DggRestResponse submitOptionsChannel(@RequestParam Map params) {
        try {
            DggValidateUtil.notNull(params.get("keyId"),CommonExcption.class,"试题关键id为空");
            DggValidateUtil.notNull(params.get("optionsId"),CommonExcption.class,"选项id为空");
            DggValidateUtil.notNull(params.get("sort"),CommonExcption.class,"选项sort为空");
            //根据选项id查询关联渠道,首先查询redis 查看是否有渠道数据
            Collection<Long> intersectionList = null;
            List<Long> channelIds = evaluatingService.findChannelIdsOptionsId(Long.parseLong(params.get("optionsId").toString()));
            int sort = Integer.parseInt(params.get("sort").toString());
            if(sort==1&&channelIds != null && channelIds.size()>0){
                DggRedisUtils.setExJson(params.get("keyId").toString(),channelIds,3600);
                return this.getSuccessResponse(channelIds);
            }else{
                List<Long> redisChannelIds = DggRedisUtils.getJson(params.get("keyId").toString(),List.class);
                if(channelIds!=null&&channelIds.size()>0&&redisChannelIds !=null&&redisChannelIds.size()>0){
                    intersectionList = CollectionUtils.intersection(redisChannelIds, channelIds);
                    DggRedisUtils.setExJson(params.get("keyId").toString(),intersectionList,3600);
                }
                return this.getSuccessResponse(intersectionList);
            }
        }catch (CommonExcption e){
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(ScProductConstant.SYS_ERROR);
        }
    }

    /**
     * 税金匹配无可用产品
     */
    @RequestMapping(value = "/customer_taxes_no_channel")
    public String customerTaxesNoChannel() {
        return "rzsc/evaluating/html/customer_taxes_no_channel";
    }
    /**
     * 税金匹配有可用产品
     */
    @RequestMapping(value = "/customer_taxes_yes_channel")
    public String customerTaxesYesChannel(String keyId,Model model) {
        if(StringUtils.isEmpty(keyId)){
            return "";
        }
        //从redis取渠道id数据
        List<Long> redisChannelIds = DggRedisUtils.getJson(keyId,List.class);
        if(redisChannelIds==null||redisChannelIds.size()==0){
            return "rzsc/evaluating/html/customer_taxes_no_channel";
        }
        //查询渠道信息
        List<EvaluatingBaseChannel> channels = evaluatingService.findChannelBatchIds(redisChannelIds);
        model.addAttribute("channels",channels);
        model.addAttribute("channelsCount",channels==null?0:channels.size());
        return "rzsc/evaluating/html/customer_taxes_yes_channel";
    }


    /**
     * 根据渠道id查询渠道关联字段信息
     */
    @RequestMapping(value = "/get_channel_field")
    @ResponseBody
    public DggRestResponse getChannelField(@RequestParam Map params) {
        try {
            DggValidateUtil.notNull(params.get("channelId"),CommonExcption.class,"渠道id为空");
            List<EvaluatingChannelField> evaluatingChannelFields = evaluatingService.queryChannelFieldByChannelId(params);
            return this.getSuccessResponse(evaluatingChannelFields);
        }catch (CommonExcption e){
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(ScProductConstant.SYS_ERROR);
        }
    }
}
